<template>
  <div class="chat-main-container">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="chat-title">
        <h3>{{ chatStore.currentSession?.title || '对话' }}</h3>
        <span class="message-count">共 {{ chatStore.answeredCount }} 轮对话</span>
      </div>
      <div class="chat-actions">
        <el-button text @click="clearCurrentSession" :disabled="!chatStore.hasActiveSession">
          <el-icon><RefreshLeft /></el-icon>
          清空对话
        </el-button>
      </div>
    </div>

    <!-- 消息列表 -->
    <div class="message-list" ref="messageListRef">
      <div v-for="(message, index) in chatStore.currentMessages" :key="message.messageId || index" 
           :class="['message', message.role]">
        
        <!-- 用户消息 -->
        <template v-if="message.role === 'user'">
          <div class="message-content">
            <div class="message-text">{{ message.content }}</div>
            <div class="message-time">{{ formatMessageTime(message.timestamp) }}</div>
          </div>
          <el-avatar class="message-avatar" :src="userAvatarUrl" :size="32" />
        </template>

        <!-- AI消息 -->
        <template v-else-if="message.role === 'assistant'">
          <el-avatar class="message-avatar" :src="aiAvatarUrl" :size="32" />
          <div class="message-content">
            <div class="message-text">
              <div class="markdown-content" v-html="renderMarkdown(message.content)"></div>
            </div>
            <div class="message-actions">
              <span class="message-time">{{ formatMessageTime(message.timestamp) }}</span>
              <el-button text size="small" @click="copyMessage(message.content)">
                <el-icon><CopyDocument /></el-icon>
                复制
              </el-button>
            </div>
          </div>
        </template>

        <!-- 系统消息 -->
        <template v-else-if="message.role === 'system'">
          <div class="system-message">
            <el-icon><InfoFilled /></el-icon>
            <span>{{ message.content }}</span>
          </div>
        </template>
      </div>

      <!-- AI思考中状态 -->
      <div v-if="chatStore.isLoading" class="message assistant">
        <el-avatar class="message-avatar" :src="aiAvatarUrl" :size="32" />
        <div class="message-content">
          <div class="thinking-indicator">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>AI正在思考中...</span>
          </div>
        </div>
      </div>

      <!-- 错误提示 -->
      <div v-if="chatStore.error" class="error-message">
        <el-alert
          :title="chatStore.error"
          type="error"
          show-icon
          :closable="true"
          @close="chatStore.clearError()"
        />
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-area">
      <div class="input-wrapper">
        <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          resize="none"
          placeholder="请输入你想对AI说的话... (Shift+Enter换行, Enter发送)"
          @keydown="handleKeydown"
          :disabled="chatStore.isLoading"
          class="message-input"
        />
        <div class="input-actions">
          <el-button 
            type="primary" 
            @click="sendMessage" 
            :disabled="!inputMessage.trim() || chatStore.isLoading || !chatStore.hasActiveSession"
            :loading="chatStore.isLoading"
            class="send-button"
          >
            <el-icon v-if="!chatStore.isLoading"><Promotion /></el-icon>
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
/**
 * 聊天主界面组件
 * 包含消息显示、发送消息、消息管理等功能
 */
import { ref, computed, nextTick, onMounted } from 'vue'
import { useChatStore } from '@/stores/chat'
import { useStore } from 'vuex'
import { ElMessage, ElMessageBox } from 'element-plus'
import { RefreshLeft, CopyDocument, InfoFilled, Loading, Promotion } from '@element-plus/icons-vue'
import config from '@/config'
import defaultAvatar from '@/assets/default-avatar.png'
import deepseekAvatar from '@/assets/deepseek-logo.png'

const chatStore = useChatStore()
const store = useStore()

// 响应式数据
const inputMessage = ref('')
const messageListRef = ref(null)

// 计算属性
const userInfo = computed(() => store.getters.getUserInfo)
const userAvatarUrl = computed(() => {
  return config.getFullResourceUrl(userInfo.value.avatarUrl) || defaultAvatar
})
const aiAvatarUrl = ref(deepseekAvatar)

/**
 * 发送消息
 */
const sendMessage = async () => {
  if (!inputMessage.value.trim() || chatStore.isLoading) return
  
  if (!chatStore.hasActiveSession) {
    ElMessage.warning('请先创建或选择一个会话')
    return
  }

  const message = inputMessage.value.trim()
  inputMessage.value = '' // 立即清空输入框

  try {
    const response = await chatStore.sendMessage(message)
    if (!response.success) {
      // 如果发送失败，可以选择恢复输入内容
      // inputMessage.value = message
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
    // inputMessage.value = message // 恢复输入内容
  }

  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}

/**
 * 处理键盘事件
 */
const handleKeydown = (event) => {
  // Enter键发送，Shift+Enter换行
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

/**
 * 滚动到消息列表底部
 */
const scrollToBottom = () => {
  if (messageListRef.value) {
    messageListRef.value.scrollTop = messageListRef.value.scrollHeight
  }
}

/**
 * 格式化消息时间
 */
const formatMessageTime = (timestamp) => {
  if (!timestamp) return ''
  
  const time = new Date(timestamp)
  const now = new Date()
  const today = new Date(now.getFullYear(), now.getMonth(), now.getDate())
  const messageDate = new Date(time.getFullYear(), time.getMonth(), time.getDate())
  
  if (messageDate.getTime() === today.getTime()) {
    // 今天的消息，只显示时间
    return time.toLocaleTimeString('zh-CN', { 
      hour: '2-digit', 
      minute: '2-digit' 
    })
  } else {
    // 其他日期的消息，显示日期和时间
    return time.toLocaleString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  }
}

/**
 * 渲染Markdown内容（简单版本）
 */
const renderMarkdown = (content) => {
  if (!content) return ''
  
  // 简单的Markdown渲染，可以后续集成更强大的Markdown库
  return content
    .replace(/\n/g, '<br>')
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
    .replace(/\*([^*]+)\*/g, '<em>$1</em>')
}

/**
 * 复制消息内容
 */
const copyMessage = async (content) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('已复制到剪贴板')
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败')
  }
}

/**
 * 清空当前会话
 */
const clearCurrentSession = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空当前对话吗？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '清空',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 这里应该调用API清空会话，暂时先清空本地状态
    if (chatStore.currentSession) {
      chatStore.currentSession.messages = []
    }
    
    ElMessage.success('对话已清空')
  } catch {
    // 用户取消
  }
}

// 生命周期
onMounted(() => {
  // 滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
})
</script>

<style scoped>
.chat-main-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f8f9fa;
}

/* 聊天头部 */
.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: #ffffff;
  border-bottom: 1px solid #e1e5e9;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.chat-title h3 {
  margin: 0 0 4px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.message-count {
  font-size: 13px;
  color: #909399;
}

/* 消息列表 */
.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  min-height: 0;
}

.message {
  display: flex;
  margin-bottom: 24px;
  align-items: flex-start;
  animation: fadeIn 0.3s ease-in;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

/* 用户消息 */
.message.user {
  justify-content: flex-end;
}

.message.user .message-content {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 18px 18px 4px 18px;
  margin-right: 12px;
  order: -1;
}

/* AI消息 */
.message.assistant {
  justify-content: flex-start;
}

.message.assistant .message-content {
  background-color: #ffffff;
  color: #333;
  border-radius: 18px 18px 18px 4px;
  margin-left: 12px;
  border: 1px solid #e1e5e9;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

/* 消息内容 */
.message-content {
  max-width: 70%;
  word-wrap: break-word;
  padding: 12px 16px;
}

.message-text {
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 8px;
}

.message-text:last-child {
  margin-bottom: 0;
}

.markdown-content {
  white-space: pre-wrap;
}

.markdown-content :deep(code) {
  background-color: #f1f2f6;
  padding: 2px 4px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
}

.message-time {
  font-size: 12px;
  opacity: 0.7;
  margin-top: 4px;
}

.message-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.message-actions .message-time {
  margin-top: 0;
}

/* 头像 */
.message-avatar {
  flex-shrink: 0;
  margin-top: 2px;
}

/* 系统消息 */
.system-message {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  background-color: #f0f9ff;
  color: #0284c7;
  border-radius: 12px;
  font-size: 13px;
  margin: 0 auto 16px;
  max-width: 400px;
}

.system-message .el-icon {
  margin-right: 6px;
}

/* 思考指示器 */
.thinking-indicator {
  display: flex;
  align-items: center;
  color: #667eea;
  font-size: 14px;
}

.thinking-indicator .el-icon {
  margin-right: 8px;
}

/* 错误消息 */
.error-message {
  margin: 16px 0;
}

/* 输入区域 */
.input-area {
  background-color: #ffffff;
  border-top: 1px solid #e1e5e9;
  padding: 20px;
  box-shadow: 0 -1px 3px rgba(0, 0, 0, 0.05);
}

.input-wrapper {
  display: flex;
  gap: 12px;
  align-items: flex-end;
}

.message-input {
  flex: 1;
}

.message-input :deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 2px solid #e1e5e9;
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.5;
  resize: none;
  transition: border-color 0.2s ease;
}

.message-input :deep(.el-textarea__inner):focus {
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
}

.send-button {
  height: 44px;
  min-width: 80px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
}

/* 滚动条样式 */
.message-list::-webkit-scrollbar {
  width: 6px;
}

.message-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-thumb:hover {
  background: #a1a1a1;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-header {
    padding: 12px 16px;
  }
  
  .message-list {
    padding: 16px;
  }
  
  .message-content {
    max-width: 85%;
    padding: 10px 12px;
  }
  
  .input-area {
    padding: 16px;
  }
  
  .input-wrapper {
    gap: 8px;
  }
  
  .send-button {
    min-width: 60px;
    height: 40px;
  }
}
</style> 